package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.WechatScanCodeLoginRequest;
import cc.rengu.igas.bsps.facade.response.WechatScanCodeLoginResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.OrderStatusEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by zhangxuran on 2020/04/15
 */
public class WechatScanCodeLoginService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        WechatScanCodeLoginRequest wechatScanCodeLoginRequest = new WechatScanCodeLoginRequest();
        ConvertUtil.convertOutput(wechatScanCodeLoginRequest);
        return wechatScanCodeLoginRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        WechatScanCodeLoginRequest wechatScanCodeLoginRequest = (WechatScanCodeLoginRequest) request;
        /*获取请求参数：法人行，登录订单号，登录URL*/
        String instId = wechatScanCodeLoginRequest.getHeader().getInstId();
        String loginOrderId = wechatScanCodeLoginRequest.getLoginOrderId();
        String loginUrl = wechatScanCodeLoginRequest.getLoginUrl();
        String userId = wechatScanCodeLoginRequest.getUserId();
        /*参数必填性校验*/
        if ((StringUtil.isEmptyOrNull(loginUrl) && StringUtil.isEmptyOrNull(loginOrderId)) || StringUtil.isEmptyOrNull(userId)) {
            rglog.error("扫码登录请求参数校验必填字段失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        /*根据登录订单号查询扫码登录订单信息*/
        UserOrderInfo userOrderInfo;
        UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
        if (!StringUtil.isEmptyOrNull(loginOrderId)) {
            userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByPrimaryKey(instId, loginOrderId);
        } else {
            userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByOrderUrl(instId, loginUrl);
        }
        if (null == userOrderInfo) {
            rglog.error("查询登录二维码订单失败！");
            throw new BizException(RespCodeEnum.GET_QRCODE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_QRCODE_INFO_ERROR.getRespDesc());
        }
        /*订单状态为非新建状态时二维码失效*/
        if (!OrderStatusEnum.INIT.getStatus().equals(userOrderInfo.getOrderStatus())) {
            rglog.error("二维码已失效！");
            throw new BizException(RespCodeEnum.EXPIRED_QRCODE_ERROR.getRespCode(), RespCodeEnum.EXPIRED_QRCODE_ERROR.getRespDesc());
        }

        /*根据微信号查询用户信息*/
        BspsUserInfoMapper bspsUserInfoMapper = new BspsUserInfoMapperImpl();
        UserInfo userInfo = bspsUserInfoMapper.selectBspsUserInfoByUserId(instId, userId);
        if (null == userInfo) {
            rglog.error("查询用户信息失败！");
            throw new BizException(RespCodeEnum.NO_REGISTER_ERROR.getRespCode(), RespCodeEnum.NO_REGISTER_ERROR.getRespDesc());
        }
        BspsMchntBindInfoMapper mchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        List<MchntBindInfo> mchntBindInfoList = mchntBindInfoMapper.selectBspsMchntBindInfoListByUserId(instId, userId);
        if (CollectionUtils.isEmpty(mchntBindInfoList)) {
            rglog.error("商户绑定信息查询失败");
            throw new BizException(RespCodeEnum.NO_REGISTER_ERROR.getRespCode(), RespCodeEnum.NO_REGISTER_ERROR.getRespDesc());
        }

        //开启事物
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        /*订单超时失效*/
        if (DateUtil.compareTime(DateUtil.getCurrentDateTime("yyyyMMddHHmmss"), userOrderInfo.getOrderExpiryTime(), "yyyyMMddHHmmss") > 0) {
            /*根据订单号更新订单状态为失效状态*/
            userOrderInfo.setOrderStatus(OrderStatusEnum.INVALID.getStatus());
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_TIMEOUT.getStatus());
            int iReTurnCode = userOrderInfoMapper.updateUserOrderInfoByUserOrderId(userOrderInfo);
            if (0 != iReTurnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("二维码登录订单更新失效状态失败！");
                throw new BizException(RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespDesc());
            }
            dbsUtil.dbsEndTransaction(true);
            throw new BizException(RespCodeEnum.EXPIRED_QRCODE_ERROR.getRespCode(), RespCodeEnum.EXPIRED_QRCODE_ERROR.getRespDesc());
        }

        /*更新用户信息到登录订单新中*/
        userOrderInfo.setUserId(userInfo.getUserId());
        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
        int iReTurnCode = userOrderInfoMapper.updateUserOrderInfoByUserOrderId(userOrderInfo);
        if (0 != iReTurnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("用户扫码登录失败！");
            throw new BizException(RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespDesc());
        }
        dbsUtil.dbsEndTransaction(true);
        /* 按照接口转换基础产品信息并响应给请求方 */
        WechatScanCodeLoginResponse wechatScanCodeLoginResponse = new WechatScanCodeLoginResponse();
        BizResponse<WechatScanCodeLoginResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(wechatScanCodeLoginResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        WechatScanCodeLoginResponse wechatScanCodeLoginResponse = (WechatScanCodeLoginResponse) bizResponse.getResult();
        ConvertUtil.convertInput(wechatScanCodeLoginResponse);
    }
}
